import cv2 
import os 

def detect(img_name):
    img = cv2.imread(img_name, cv2.IMREAD_COLOR)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    cascade_file = os.getcwd() + '/dev/lbpcascade_animeface.xml'
    cascade = cv2.CascadeClassifier(cascade_file)

    faces = cascade.detectMultiScale(gray,
                                    # detector options
                                    scaleFactor = 1.1,
                                    minNeighbors = 5,
                                    minSize = (24, 24))
    
    for (x, y, w, h) in faces:
        # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)

        img  = img[y:y+h, x:x+w]

    if img_name.endswith(".jpg"):
        save_name =  str(img_name).replace('.jpg', '_head.jpg')
    if img_name.endswith(".png"):
        save_name =  str(img_name).replace('.png', '_head.jpg')

    cv2.imwrite(save_name, img)
    # cv2.imshow('1', img)
    # cv2.waitKey(0)

